<template>
	<view class="review-container">
		<view class="header">
			<text class="title">参观评价</text>
			<text class="subtitle">请对您的参观体验进行评价</text>
		</view>
		
		<!-- Debug indicator - normally hidden -->
		<view class="state-indicator" v-if="false">
			<text>Review状态: {{ existingReview ? '已有评价' : '可以评价' }}</text>
		</view>
		
		<view class="reservation-info" v-if="reservation">
			<view class="info-card">
				<view class="exhibition-info" v-if="reservation.exhibitionTitle">
					<text class="exhibition-title">{{ reservation.exhibitionTitle }}</text>
				</view>
				<view class="info-grid">
					<view class="info-item">
						<view class="label">
							<uni-icons type="calendar" size="18" color="#666"></uni-icons>
							<text>预约日期</text>
						</view>
						<text class="value">{{ reservation.visitDate }}</text>
					</view>
					<view class="info-item">
						<view class="label">
							<uni-icons type="clock" size="18" color="#666"></uni-icons>
							<text>参观时间</text>
						</view>
						<text class="value">{{ reservation.visitTimeSlot }}</text>
					</view>
					<view class="info-item">
						<view class="label">
							<uni-icons type="person" size="18" color="#666"></uni-icons>
							<text>参观人数</text>
						</view>
						<text class="value">{{ reservation.visitorCount }}人</text>
					</view>
					<view class="info-item" v-if="reservation.status !== undefined">
						<view class="label">
							<uni-icons type="info" size="18" color="#666"></uni-icons>
							<text>预约状态</text>
						</view>
						<text class="value status" :class="getStatusClass(reservation.status)">
							{{ getStatusText(reservation.status) }}
						</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- Review form section - only show when no existing review -->
		<view v-if="!existingReview" class="review-form-section">
			<view class="rating-section">
				<text class="section-title">整体满意度</text>
				<view class="score-selector">
					<text class="score-label">请为此次参观打分（1-10分）</text>
					<view class="score-slider">
						<slider 
							:value="rating" 
							min="1" 
							max="10" 
							show-value 
							activeColor="#1890FF"
							block-color="#1890FF"
							@change="onRatingChange"
						/>
					</view>
					<text class="score-value">{{ rating }}分</text>
					<text class="rating-text">{{ getRatingText(rating) }}</text>
				</view>
			</view>
			
			<view class="content-section">
				<text class="section-title">评价内容</text>
				<textarea 
					v-model="content" 
					class="review-content" 
					placeholder="请分享您的参观体验，您的反馈对我们非常重要..." 
					maxlength="500"
				></textarea>
				<text class="word-count">{{ content.length }}/500</text>
			</view>
			
			<view class="action-buttons">
				<button class="cancel-btn" @click="goBack">取消</button>
				<button class="submit-btn" @click="submitReviewBtn()" :disabled="!canSubmit">提交评价</button>
			</view>
		</view>
		
		<!-- 已评价展示 -->
		<view class="existing-review" v-if="existingReview">
			<view class="review-header">
				<text class="review-title">我的评价</text>
				<view class="review-score">
					<text class="score-number">{{ existingReview.score }}分</text>
				</view>
			</view>
			<view class="review-time">{{ formatDateTime(existingReview.createTime) }}</view>
			<view class="review-satisfaction">{{ getRatingText(existingReview.score) }}</view>
			<view class="review-content">{{ existingReview.content }}</view>
			
			<view class="reply-section" v-if="existingReview.reply">
				<view class="reply-header">
					<uni-icons type="staff" size="20" color="#1890FF"></uni-icons>
					<text class="reply-title">管理员回复</text>
				</view>
				<view class="reply-time" v-if="existingReview.replyTime">{{ formatDateTime(existingReview.replyTime) }}</view>
				<view class="reply-content"><text>{{ existingReview.reply }}</text></view>
			</view>
		</view>
		
		<!-- Debug info -->
		<view class="debug-section" v-if="false">
			<text class="debug-title">调试信息</text>
			<view class="debug-item">
				<text class="debug-label">existingReview:</text>
				<text class="debug-value">{{ existingReview ? '有' : '无' }}</text>
			</view>
			<view class="debug-item" v-if="existingReview">
				<text class="debug-label">评分:</text>
				<text class="debug-value">{{ existingReview.score }}</text>
			</view>
			<view class="debug-item" v-if="existingReview">
				<text class="debug-label">内容:</text>
				<text class="debug-value">{{ existingReview.content }}</text>
			</view>
		</view>
	</view>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue';
import { submitReview, getReservationReview } from '@/api/review.js';
import { getReservationDetail } from '@/api/reservation.js';

export default {
	setup() {
		const reservation = ref(null);
		const existingReview = ref(null);
		const rating = ref(10);
		const content = ref('');
		const reservationId = ref(null);
		const userId = ref(null);
		const isLoading = ref(false);
		
		// 初始化
		onMounted(() => {
			initializeReview();
		});

		// 统一初始化函数，便于阅读和维护
		const initializeReview = () => {
			const query = uni.getLaunchOptionsSync().query || {};
			const pages = getCurrentPages();
			const page = pages[pages.length - 1];
			const id = page.options?.id || query.id;
			
			if (!id) {
				handleError('无效的预约ID');
				return;
			}
			
			reservationId.value = id;
			
			// 获取用户信息
			const userInfo = uni.getStorageSync('userInfo');
			if (!userInfo) {
				handleError('请先登录', '/pages/login/index');
				return;
			}
			
			userId.value = userInfo.id;
			
			// 加载数据
			loadReservationData(id);
		};
		
		// 加载预约详情和评价
		const loadReservationData = (id) => {
			isLoading.value = true;
			uni.showLoading({ title: '加载中...' });
			
			// 并行加载预约详情和评价数据
			Promise.all([
				loadReservation(id),
				checkExistingReview(id)
			])
			.finally(() => {
				isLoading.value = false;
				uni.hideLoading();
				
				// 安全超时：确保表单能够显示，即使API有问题
				setTimeout(() => {
					if (existingReview.value === null && isLoading.value) {
						console.log('超时保障：确保评价表单可见');
						existingReview.value = null;
						isLoading.value = false;
					}
				}, 3000);
			});
		};
		
		// 统一错误处理
		const handleError = (message, redirectUrl = null) => {
			uni.showToast({
				title: message,
				icon: 'none'
			});
			
			if (redirectUrl) {
				setTimeout(() => {
					uni.navigateTo({ url: redirectUrl });
				}, 1500);
			} else {
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
			}
		};
		
		// 加载预约详情
		const loadReservation = async (id) => {
			try {
				const res = await getReservationDetail(id);
				console.log('预约详情数据:', res);
				if (res.code === 200) {
					// 数据转换：将下划线格式转为驼峰格式
					const data = res.data;
					reservation.value = {
						id: data.id,
						userId: data.userId,
						visitorCount: data.visitor_count || 0,
						visitDate: data.visit_date || '',
						visitTimeSlot: data.visit_time_slot || '',
						status: data.status !== undefined ? Number(data.status) : 1, // 确保status是数字类型
						createTime: data.create_time,
						exhibitionTitle: data.exhibition_title || '博物馆参观',
						// 其他字段...
					};
					console.log('处理后的预约数据:', reservation.value);
					return reservation.value;
				} else {
					throw new Error(res.message || '获取预约详情失败');
				}
			} catch (error) {
				console.error('获取预约详情失败:', error);
				uni.showToast({
					title: error.message || '网络错误，请稍后重试',
					icon: 'none'
				});
				return null;
			}
		};
		
		// 检查是否已有评价
		const checkExistingReview = async (id) => {
			console.log('开始检查评价, ID:', id);
			try {
				const res = await getReservationReview(id);
				console.log('获取评价响应:', res);
				
				if (res.code === 200 && res.data) {
					console.log('评价数据:', res.data);
					// 确保正确设置existingReview对象
					const score = res.data.score ? Number(res.data.score) : 10;
					existingReview.value = {
						id: res.data.id,
						reservationId: res.data.reservationId,
						userId: res.data.userId,
						content: res.data.content || '',
						reply: res.data.reply || null,
						score: score, // 确保是数字类型
						createTime: res.data.createTime,
						replyTime: res.data.replyTime
					};
					
					// 如果已有评价，同步更新表单
					rating.value = score;
					content.value = existingReview.value.content;
					console.log('设置表单值 - 评分:', rating.value, '满意度:', getRatingText(rating.value), '内容:', content.value);
					console.log('设置后的existingReview:', existingReview.value);
					return existingReview.value;
				} else {
					console.log('没有找到评价数据或响应异常');
					existingReview.value = null;
					return null;
				}
			} catch (error) {
				console.error('检查评价失败:', error);
				
				// 该预约暂无评价的情况，是正常情况（无论服务器返回的状态码是什么）
				if (error && 
					(error.code === 404 || 
					 error.code === 500 || 
					 error.message === '该预约暂无评价')
				) {
					console.log('该预约尚未评价，可以创建新评价');
					existingReview.value = null;
				}
				
				return null;
			}
		};
		
		// 预约状态文本
		const getStatusText = (status) => {
			const statusMap = {
				0: '待审核',
				1: '已确认',
				2: '已失效',
			};
			// 先将status转为数字类型，避免字符串比较问题
			const numStatus = Number(status);
			return statusMap[numStatus] || '未知状态';
		};
		
		// 预约状态类名
		const getStatusClass = (status) => {
			const classMap = {
				0: 'status-pending',
				1: 'status-confirmed',
				2: 'status-cancelled',
				3: 'status-completed'
			};
			// 先将status转为数字类型
			const numStatus = Number(status);
			return classMap[numStatus] || '';
		};
		
		// onRatingChange handler for slider
		const onRatingChange = (e) => {
			rating.value = e.detail.value;
		};
		
		// 获取评分文字描述
		const getRatingText = (score) => {
			// 确保score是数字
			const numScore = Number(score) || 10;
			
			// 根据分数返回对应的满意度文本
			if (numScore >= 9) return '非常满意';
			if (numScore >= 7) return '满意';
			if (numScore >= 5) return '一般';
			if (numScore >= 3) return '不满意';
			return '非常不满意';
		};
		
		// 是否可以提交
		const canSubmit = computed(() => {
			return content.value.trim().length > 0 && rating.value > 0;
		});
		
		// 日期时间格式化函数
		const formatDateTime = (dateString, fallback = '') => {
			if (!dateString) return fallback;
			
			try {
				const date = new Date(dateString);
				if (isNaN(date.getTime())) return fallback;
				
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				const hours = String(date.getHours()).padStart(2, '0');
				const minutes = String(date.getMinutes()).padStart(2, '0');
				
				return `${year}-${month}-${day} ${hours}:${minutes}`;
			} catch (e) {
				return fallback;
			}
		};
		
		// 提交评价
		const submitReviewBtn = async () => {
			if (!canSubmit.value) {
				uni.showToast({
					title: '请填写评价内容',
					icon: 'none'
				});
				return;
			}
			
			if (!reservationId.value || !userId.value) {
				uni.showToast({
					title: '参数错误',
					icon: 'none'
				});
				return;
			}
			
			uni.showLoading({ title: '提交中...' });
			
			try {
				const data = {
					reservationId: reservationId.value,
					userId: userId.value,
					content: content.value,
					score: rating.value
				};
				
				console.log('提交评价数据:', data);
				console.log(12121);
				
				const res = await submitReview(data);
				console.log('提交评价结果:', res);
				
				if (res.code === 200) {
					uni.showToast({
						title: '评价提交成功',
						icon: 'success'
					});
					
					// 构建评价对象
					const newReview = {
						id: Date.now(), // 临时ID
						reservationId: reservationId.value,
						userId: userId.value,
						content: content.value,
						score: rating.value,
						createTime: new Date(),
						reply: null,
						replyTime: null
					};
					
					// 直接更新本地状态，避免再次请求
					setTimeout(() => {
						existingReview.value = newReview;
						console.log('提交后更新existingReview:', existingReview.value);
					}, 500);
				} else {
					uni.showToast({
						title: res.message || '评价提交失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('提交评价失败:', error);
				uni.showToast({
					title: '网络错误，请稍后重试',
					icon: 'none'
				});
			} finally {
				uni.hideLoading();
			}
		};
		
		// 返回上一页
		const goBack = () => {
			uni.navigateBack();
		};
		
		return {
			reservation,
			existingReview,
			rating,
			content,
			onRatingChange,
			getRatingText,
			canSubmit,
			formatDateTime,
			submitReviewBtn,
			goBack,
			getStatusText,
			getStatusClass
		};
	}
};
</script>

<style lang="scss">
.review-container {
	min-height: 100vh;
	background-color: #f5f5f5;
	padding: 30rpx;
	
	.header {
		margin-bottom: 40rpx;
		
		.title {
			font-size: 36rpx;
			font-weight: bold;
			color: #333;
			margin-bottom: 10rpx;
			display: block;
		}
		
		.subtitle {
			font-size: 28rpx;
			color: #666;
		}
	}
	
	.reservation-info {
		margin-bottom: 30rpx;
		
		.info-card {
			background-color: #fff;
			border-radius: 12rpx;
			overflow: hidden;
			box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
			
			.exhibition-info {
				background-color: #1890FF;
				padding: 20rpx 30rpx;
				
				.exhibition-title {
					color: #fff;
					font-size: 30rpx;
					font-weight: 500;
				}
			}
			
			.info-grid {
				padding: 30rpx;
				display: grid;
				grid-template-columns: repeat(2, 1fr);
				gap: 24rpx;
				
				.info-item {
					.label {
						display: flex;
						align-items: center;
						margin-bottom: 8rpx;
						
						text {
							color: #666;
							font-size: 26rpx;
							margin-left: 6rpx;
						}
					}
					
					.value {
						color: #333;
						font-size: 28rpx;
						font-weight: 500;
						
						&.status {
							border-radius: 20rpx;
							padding: 4rpx 16rpx;
							font-size: 24rpx;
							display: inline-block;
							
							&.status-pending {
								background-color: #E6F7FF;
								color: #1890FF;
							}
							
							&.status-confirmed {
								background-color: #F6FFED;
								color: #52C41A;
							}
							
							&.status-cancelled {
								background-color: #FFF1F0;
								color: #FF4D4F;
							}
							
							&.status-completed {
								background-color: #F9F0FF;
								color: #722ED1;
							}
						}
					}
				}
			}
		}
	}
	
	.rating-section, .content-section {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
		
		.section-title {
			font-size: 30rpx;
			font-weight: 500;
			color: #333;
			margin-bottom: 20rpx;
			display: block;
		}
	}
	
	.rating-section {
		.score-selector {
			display: flex;
			flex-direction: column;
			align-items: center;
			margin: 20rpx 0;
			
			.score-label {
				font-size: 28rpx;
				color: #666;
				margin-bottom: 20rpx;
			}
			
			.score-slider {
				width: 100%;
				padding: 0 20rpx;
			}
			
			.score-value {
				font-size: 48rpx;
				font-weight: bold;
				color: #1890FF;
				margin: 20rpx 0;
			}
		}
		
		.rating-text {
			text-align: center;
			display: block;
			font-size: 28rpx;
			color: #666;
			margin-top: 10rpx;
		}
	}
	
	.content-section {
		.review-content {
			width: 100%;
			height: 240rpx;
			background-color: #f9f9f9;
			border-radius: 8rpx;
			padding: 20rpx;
			font-size: 28rpx;
			color: #333;
			box-sizing: border-box;
		}
		
		.word-count {
			text-align: right;
			font-size: 24rpx;
			color: #999;
			margin-top: 10rpx;
			display: block;
		}
	}
	
	.action-buttons {
		display: flex;
		justify-content: space-between;
		padding: 30rpx 0;
		
		.cancel-btn, .submit-btn {
			flex: 1;
			margin: 0 15rpx;
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			border-radius: 40rpx;
			font-size: 30rpx;
		}
		
		.cancel-btn {
			background-color: #f5f5f5;
			color: #666;
			border: 1px solid #ddd;
		}
		
		.submit-btn {
			background-color: #1890FF;
			color: #fff;
			
			&:disabled {
				background-color: #ccc;
				color: #fff;
			}
		}
	}
	
	.existing-review {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
		
		.review-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 16rpx;
			
			.review-title {
				font-size: 30rpx;
				font-weight: 500;
				color: #333;
			}
			
			.review-score {
				.score-number {
					font-size: 32rpx;
					font-weight: bold;
					color: #1890FF;
				}
			}
		}
		
		.review-time {
			font-size: 24rpx;
			color: #999;
			margin-bottom: 10rpx;
		}
		
		.review-satisfaction {
			font-size: 28rpx;
			color: #FF9500;
			font-weight: 500;
			margin-bottom: 20rpx;
		}
		
		.review-content {
			width: 100%;
			font-size: 28rpx;
			color: #333;
			line-height: 1.6;
			margin-bottom: 30rpx;
		}
		
		.reply-section {
			background-color: #f9f9f9;
			border-radius: 8rpx;
			padding: 20rpx;
			
			.reply-header {
				display: flex;
				align-items: center;
				margin-bottom: 10rpx;
				
				.reply-title {
					font-size: 28rpx;
					color: #1890FF;
					font-weight: 500;
					margin-left: 10rpx;
				}
			}
			
			.reply-time {
				font-size: 24rpx;
				color: #999;
				margin-bottom: 16rpx;
			}
			
			.reply-content {
				font-size: 28rpx;
				color: #333;
				line-height: 1.6;
				white-space: normal;
				word-break: break-all;
				overflow-wrap: break-word;
				max-width: 100%;
			}
		}
	}
	
	.debug-section {
		margin-top: 30rpx;
		padding: 30rpx;
		background-color: #fff;
		border-radius: 12rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
		
		.debug-title {
			font-size: 30rpx;
			font-weight: 500;
			color: #333;
			margin-bottom: 20rpx;
		}
		
		.debug-item {
			display: flex;
			justify-content: space-between;
			margin-bottom: 10rpx;
			
			.debug-label {
				color: #666;
				font-size: 28rpx;
			}
			
			.debug-value {
				color: #333;
				font-size: 28rpx;
				font-weight: 500;
			}
		}
	}
}
</style> 